<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>处理ajax响应</title>
    <style>
        #box {
          width: 200px;
          height: 200px;
          border: 1px solid #666;
        }
      </style>
</head>
<body>
    <button id="textBtn">AJAX 获取Text</button>
    <button id="jsonBtn">AJAX 获取JSON</button>

    <div id="box"></div>
    <script>
        let xhr;
        document.getElementById('textBtn').onclick = ()=>{
            xhr = new XMLHttpRequest()
            xhr.open('get','http://localhost:9812/text-server')
            xhr.send()
        
        // 4.绑定状态改变的监听
        xhr.onreadystatechange = ()=>{
            console.log('onreadystatechange readState',xhr.readyState);
            // 如果请求已经完成,才去取数据
            if(xhr.readyState === 4){
                // 响应状态码
                console.log(xhr.status);
                //响应头
                console.log(xhr.getResponseHeader('Content-Type'));
                // 响应体
                console.log(xhr.responseText);

                // 显示响应体
                document.getElementById('box').innerHTML = xhr.responseText;
            }
        }
        }

        document.getElementById('jsonBtn').onclick = ()=>{
            const xhr = new XMLHttpRequest()
            xhr.open('get','http://localhost:9812/json-server')
            xhr.send()
        
        // 4.绑定状态改变的监听
        xhr.onreadystatechange = ()=>{
            console.log('onreadystatechange readState',xhr.readyState);
            // 如果请求已经完成,才去取数据
            if(xhr.readyState === 4){
                // 响应状态码
                console.log(xhr.status);
                //响应头
                console.log(xhr.getResponseHeader('Content-Type'));
                // 响应体
                // console.log(xhr.responseText);

                //将得到的json文本解析为js对象
                const obj  = JSON.parse(xhr.responseText)

                //提示
                alert(obj.code +'-'+obj.msg)
                // 显示响应体
                document.getElementById('box').innerHTML = xhr.responseText;
            }
        } 
        }







    </script>
</body>
</html>